package com.cugmarket.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cugmarket.constant.RedisConstants;
import com.cugmarket.entity.ChatMessage;
import com.cugmarket.exception.BaseException;
import com.cugmarket.mapper.ChatMessageMapper;
import com.cugmarket.service.ChatMessageService;
import com.cugmarket.service.UserService;
import com.cugmarket.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import static com.cugmarket.constant.MessageConstant.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage> implements ChatMessageService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserService userService;


    /**
     * 根据chatListId获取所有聊天消息
     * @param chatListId
     * @return
     */
    @Override
    public List<ChatMessage> getChatMessageList(String chatListId) {
        //判断redis中是否还有数据没有保存数据库
        List<ChatMessage> redisMessages = new ArrayList<>();
        ListOperations<String, String> operations = redisTemplate.opsForList();
        List<String> messageList = operations.range(RedisConstants.CHAT_LIST_KEY + chatListId, 0, -1);
        if(messageList!=null){
            redisMessages = getMessageListFromRedis(messageList);
        }
        // 获取数据库中数据
        List<ChatMessage> dbMessages = lambdaQuery().eq(ChatMessage::getChatListId, chatListId).orderByAsc(ChatMessage::getSendTime).list();
        dbMessages.addAll(redisMessages);
        dbMessages.sort(Comparator.comparing(ChatMessage::getSendTime));
        return dbMessages;
    }

    /**
     * 更新消息为已读
     * @param chatListId
     */
    @Override
    public void updateChatMessageIsRead(String chatListId) {
        //获取redis中数据
        ListOperations<String, String> operations = redisTemplate.opsForList();
        List<String> messageListRedis = operations.range(RedisConstants.CHAT_LIST_KEY + chatListId, 0, -1);
        if (messageListRedis != null && !messageListRedis.isEmpty()) {
            boolean result = saveMessages(messageListRedis);
            if (result) {
                redisTemplate.delete(RedisConstants.CHAT_LIST_KEY + chatListId);
            } else {
                throw new BaseException(DELETE_ERROR);
            }
        }
        //获取数据库中未读数据
        List<ChatMessage> dbMessagesNoRead = lambdaQuery().eq(ChatMessage::getChatListId, chatListId)
                .eq(ChatMessage::getToUserId, UserHolder.getUser())
                .eq(ChatMessage::getIsRead, 0)
                .list();
        for (ChatMessage chatMessage : dbMessagesNoRead) {
            chatMessage.setIsRead(1);
            boolean update = updateById(chatMessage);
            if (!update) throw new BaseException(UPDATE_ERROR);
        }
    }

    /**
     * 将redis中的消息转换为对象后保存进数据库
     * @param chatMessages
     * @return
     */
    @Override
    public boolean saveMessages(List<String> chatMessages) {
        if (chatMessages == null || chatMessages.isEmpty()) {
            return false;
        }
        // 将 JSON 转换为 ChatMessage 对象
        List<ChatMessage> chatMessageList = getMessageListFromRedis(chatMessages);
        // 使用 MyBatis Plus 批量插入
        boolean saveBatch = saveBatch(chatMessageList);
        if(!saveBatch){
            // 如果批量插入失败，抛出自定义异常
            throw new BaseException(INSERT_ERROR);
        }
        return true ;
    }

    /**
     * 将redis中的消息转换为ChatMessage类型的数组
     * @param chatMessages
     * @return
     */
    public List<ChatMessage> getMessageListFromRedis(List<String> chatMessages) {
        // 将 JSON 转换为 ChatMessage 对象
        List<ChatMessage> chatMessageList = chatMessages.stream()
                .map(message -> {
                    ChatMessage chatMessage = new ChatMessage();
                    try {
                        JSONObject jsonObject = JSON.parseObject(message);
                        chatMessage.setChatListId(jsonObject.getString("chatListId"));
                        chatMessage.setFromUserId(jsonObject.getString("fromUserId"));
                        chatMessage.setFromUserAvatar(jsonObject.getString("fromUserAvatar"));
                        chatMessage.setFromUserNick(jsonObject.getString("fromUserNick"));
                        chatMessage.setToUserId(jsonObject.getString("toUserId"));
                        chatMessage.setToUserAvatar(jsonObject.getString("toUserAvatar"));
                        chatMessage.setToUserNick(jsonObject.getString("toUserNick"));
                        chatMessage.setContent(jsonObject.getString("content"));
                        chatMessage.setIsRead(Integer.parseInt(jsonObject.getString("isRead")));

                        // 解析 sendTime
                        String sendTimeString = jsonObject.getString("sendTime");
                        if (sendTimeString != null && !sendTimeString.isEmpty()) {
                            SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
                            isoFormat.setTimeZone(TimeZone.getTimeZone("UTC")); // 解析为 UTC 时间
                            Date sendTime = isoFormat.parse(sendTimeString);
                            chatMessage.setSendTime(sendTime); // 设置到 ChatMessage 中
                        } else {
                            // 如果 sendTime 为空，则设置为当前时间或其他默认值
                            chatMessage.setSendTime(new Date());
                        }

                    } catch (Exception e) {
                        // 捕获解析异常，打印日志或处理错误
                        throw new BaseException(e.getMessage());
                    }
                    return chatMessage;
                })
                .collect(Collectors.toList());
        return chatMessageList;
    }
}
